package com.cloud.config;

import com.cloud.handler.LogHandler;
import com.cloud.util.BaseContextUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class CloudLogRecordFeignConfig {

    @Value("${spring.application.name:default-application}")
    private String applicationName;

    @Bean("cloudLogRequestInterceptor")
    public RequestInterceptor requestInterceptor() {
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、使用RequestContextHolder拿到刚进来的请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (requestAttributes != null) {
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    if (request != null) {
                        //2、同步请求头的数据（主要是cookie）
                        //把老请求的cookie值放到新请求上来，进行一个同步
//                        String cookie = request.getHeader("Cookie");
//                        if (StringUtils.isBlank(request.getHeader(LogHandler.TRACE_ID))) {
                        template.header(LogHandler.TRACE_ID, (String) BaseContextUtil.get(LogHandler.TRACE_ID));
//                        }
//                        if (StringUtils.isBlank(request.getHeader(LogHandler.SOURCE_NAME))) {
                        template.header(LogHandler.SOURCE_NAME, applicationName);
//                        }
//                        if (StringUtils.isBlank(request.getHeader(LogHandler.PARENT_SPAN_ID))) {
                        template.header(LogHandler.PARENT_SPAN_ID, (String) BaseContextUtil.get(LogHandler.SPAN_ID));
//                        }
                    }
                }
            }
        };
        return requestInterceptor;
    }
}
